<template>
  <div class="login">
    <div class="loginPart">
      <h2>用户权限修改</h2>

      <!-- 权限修改弹窗 -->
      <el-dialog title="用户权限修改" v-model="dialogVisible">
        <el-form
            ref="ruleFormRef"
            :model="user"
            label-width="100px"
            class="demo-ruleForm"
        >
          <el-form-item label="用户名：" prop="account">
            <el-input v-model="user.username" placeholder="请输入用户名" maxlength="20" clearable />
          </el-form-item>

          <el-form-item label="权限：" prop="userpri">
            <el-select v-model="user.userpri" placeholder="请选择权限">
              <el-option
                  v-for="item in userRoles"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>

          <div class="btn">
            <el-button type="primary" @click="onSubmit(ruleFormRef)">提交修改</el-button>
          </div>
        </el-form>
      </el-dialog>

      <!-- 搜索框 -->
      <el-input type="text" v-model="searchInput" @input="searchUser" style="width: 240px; margin-left: 20px" :suffix-icon="Search"/>
      <!-- 权限修改按钮 -->
      <el-button type="primary" @click="dialogVisible = true" style="margin-left: 20px">修改用户权限</el-button>
      <!-- 用户列表 -->
      <el-table :data="filteredUsers" style="width: 100%">
        <el-table-column prop="fields.userName" label="用户名"></el-table-column>
        <el-table-column prop="fields.userPsw" label="密码">
          <template #default="scope">
            {{ isPasswordVisible(scope.$index) ? scope.row.fields.userPsw : maskPassword }}
          </template>
        </el-table-column>
        <el-table-column prop="fields.userPri" label="权限">
          <template #default="scope">
            {{ getUserRole(scope.row.fields.userPri) }}
          </template>
        </el-table-column>
        <el-table-column label="查看密码">
          <template #default="scope">
            <el-button type="text" @click="togglePasswordVisibility(scope.$index)">查看密码</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref, computed } from 'vue'
import { login, regist, modifyPri, showUsers } from '@/api/Login'
import type { FormInstance } from 'element-plus'
import { encode, decode } from 'js-base64'
import { ElMessage } from 'element-plus'
import { Plus, Search, Delete } from '@element-plus/icons-vue'

const list = ref([
  {
    model: "backend.users",
    pk: 1,
    fields: {
      userName: '',
      userPsw: '',
      userPri: ''
    }
  }
]);

const userRoles = [
  { value: 3, label: '管理员' },
  { value: 2, label: '守卫' },
  { value: 1, label: '普通用户' },
  { value: 4, label: '护工' }
];

const fetchData = async () => {
  try {
    const response = await showUsers();
    list.value = response.data.list;
  } catch (error) {
    console.error(error);
  }
};

const searchInput = ref("");
const passwordVisible = ref([]);
const adminPassword = "admin123";

fetchData();

const filteredUsers = computed(() => {
  return list.value.filter(user => user.fields.userName.includes(searchInput.value));
});

const maskPassword = computed(() => {
  return "*".repeat(5);
});

function getUserRole(userPri) {
  switch (userPri) {
    case 4:
      return '护工';
    case 3:
      return '管理员';
    case 2:
      return '守卫';
    case 1:
      return '普通用户';
    default:
      return '未定义';
  }
}

function togglePasswordVisibility(index) {
  if (passwordVisible.value[index]) {
    passwordVisible.value[index] = false;
  } else {
    showPasswordModal(index);
  }
}

function showPasswordModal(index) {
  const inputPassword = prompt("请输入管理员密码");
  if (inputPassword === adminPassword) {
    passwordVisible.value[index] = true;
  } else {
    alert("管理员密码错误");
  }
}

function isPasswordVisible(index) {
  return passwordVisible.value[index];
}

function searchUser() {
  passwordVisible.value = []
}

const ruleFormRef = ref<FormInstance>()
const user = reactive({
  username: '',
  userpri: ''
})
const dialogVisible = ref(false)

const onSubmit = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate((valid) => {
    if (valid) {
      const requestData = {
        username: user.username,
        userpri: user.userpri
      };
      modifyPri(requestData)
          .then((response) => {
            console.log(requestData)
            var res = response.data
            if (res.respCode === '000000') {
              ElMessage.success('修改成功');
              dialogVisible.value = false;
              fetchData();
            } else {
              ElMessage.error(res.respMsg);
            }
          })
          .catch((error) => {
            console.error(error);
            ElMessage.error('修改失败，请重试');
          });
    } else {
      ElMessage.error('错误的提交！');
    }
  });
}
</script>

<style scoped>
.login {
  display: flex;
  flex-direction: column;
  align-items: center;
  height: 100vh;
}

.loginPart {
  width: 80%;
  padding: 40px;
  margin: 30px;
  background-color: #fff;
  border-radius: 10px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
}

.el-form-item {
  display: flex;
  align-items: center;
}

.btn {
  display: flex;
  justify-content: end;
  margin-top: 20px;
}

.el-table {
  width: 100%;
}

.el-table th,
.el-table td {
  padding: 10px;
  text-align: center;
}

.btn-blue {
  color: #4682B4;
}
.btn-blue:hover {
  background: #4682B4;
  color: #fff;
}
</style>
